package httpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class httpSolver {
	Socket incomingSocket;
	String root;
	public httpSolver(Socket incomingSocket,String root) {
		this.incomingSocket=incomingSocket;
		this.root=root;
	}

	public void serve()
	{

		Scanner in=null;
		
		OutputStream out=null;
		try {
			in=new Scanner(incomingSocket.getInputStream());
//			out=new PrintWriter(incomingSocket.getOutputStream(),true);
			out=incomingSocket.getOutputStream();
			HttpMessage httpMessage=new HttpMessage();
			httpMessage.root=root;
			while(in.hasNextLine())
			{
				String input=in.nextLine();
				
				String splitResult[]=null;
				if(input.startsWith("GET")||input.startsWith("get"))
				{
					splitResult=input.split(new String(" "));
					
					if(!splitResult[2].equals("HTTP/1.1"))
					{
						new badRequest().work(out);
						incomingSocket.close();
						break;
					}
					if(splitResult[1].equals("/"))
					{
						httpMessage.targetFile="index.html";
					}
					else
					{
						httpMessage.targetFile=splitResult[1].substring(1,splitResult[1].length());
					}
				}
				else
				{
					splitResult=input.split(new String(":"));
					switch (splitResult[0]) {
					case "If-Modified-Since":
						httpMessage.If_Modified_Since=true;
						httpMessage.If_Modified_SinceString=splitResult[1];
						break;
					case "":
						new GetDisk(httpMessage).work(out);
						incomingSocket.close();
						break;
					default:
						
						break;
						
						
					}
					
				}
				

			}

		}			
		catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("socket io exception");
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(in!=null)
				{
					in.close();
				}
				if(out!=null)
				{
					out.close();
				}

			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}

	}
}

